import request from '@/utils/request';
import type { ApiResult } from '@/api';
import type { Menu, MenuParam } from './model';
import { MenuItemType } from 'ele-admin-pro';

/**
 * 获取当前登录菜单
 */
export async function getUserMenus(): Promise<MenuItemType[]> {
  const res = await request.get<ApiResult<MenuItemType[]>>(
    '/sysMenu/loginMenuTree'
  );
  if (res.data.code === 200 && res.data.result) {
    return res.data.result;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询菜单列表
 */
export async function listMenus(params: MenuParam) {
  const res = await request.get<ApiResult<Menu[]>>('/sysMenu/list', {
    params
  });
  if (res.data.code === 200) {
    return res.data.result;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加菜单
 */
export async function addMenu(data: Menu) {
  const res = await request.post<ApiResult<unknown>>('/sysMenu/add', data);
  if (res.data.code === 200) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改菜单
 */
export async function updateMenu(data: Menu) {
  const res = await request.post<ApiResult<unknown>>('/sysMenu/update', data);
  if (res.data.code === 200) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除菜单
 */
export async function removeMenu(id?: number) {
  const res = await request.post<ApiResult<unknown>>('/sysMenu/delete', {
    id
  });
  if (res.data.code === 200) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
